using System;
using System.Web.Mvc;
using iHouse.Common.Const;
using iHouse.Infrastructure;
using iHouse.Model.Data;
using iHouse.Model.Repository.Interface;
using iHouse.Resource;
using iHouse.Web.Infrastructure;
using Microsoft.Practices.Unity;

namespace iHouse.Web.Areas.Admin.Controllers
{
    [Authorize]
    public class CategoryController : Controller
    {
        [Dependency]
        public ICategoryRepository CategoryRespository { get; set; }

        //
        // GET: Get items for jqGrid
        public ActionResult GetGridData([PaingCriteriaBinder(typeof(CategorySearchFilter))]PagingCriteria pagingCriteria, int? typeID)
        {
            var list = CategoryRespository.GetCategoriesForList(typeID.GetValueOrDefault(), pagingCriteria);

            return Json(list.ToJsonCategoryEntity(), JsonRequestBehavior.AllowGet);
        }

        //
        // POST: /Category/Create
        [AcceptVerbs(HttpVerbs.Post)]
        [JsonException]
        public void Create()
        {
            if (string.IsNullOrEmpty(this.HttpContext.Request.Form[BusinessConst.NAME_FIELD]))
            {
                throw new Exception(Resources.ExceptionCategoryWithName);
            }

            int typeID = 0;
            if (!int.TryParse(this.HttpContext.Request.Form[BusinessConst.TYPE_FIELD], out typeID) || typeID == 0)
            {
                throw new Exception(Resources.ExceptionCategoryWithType);
            }

            Category cate = new Category();
            cate.Name = this.HttpContext.Request.Form[BusinessConst.NAME_FIELD];
            cate.TypeID = Convert.ToInt32(this.HttpContext.Request.Form[BusinessConst.TYPE_FIELD]);

            CategoryRespository.CreateCategory(cate);
        }

        //
        // POST: /Category/Update/5
        [AcceptVerbs(HttpVerbs.Post)]
        [JsonException]
        public void Update(int id)
        {
            if (string.IsNullOrEmpty(this.HttpContext.Request.Form[BusinessConst.NAME_FIELD]))
            {
                throw new Exception(Resources.ExceptionCategoryWithName);
            }

            int typeID = 0;
            if (!int.TryParse(this.HttpContext.Request.Form[BusinessConst.TYPE_FIELD], out typeID) || typeID == 0)
            {
                throw new Exception(Resources.ExceptionCategoryWithType);
            }

            Category cate = CategoryRespository.GetCategoryByID(id);
            cate.Name = this.HttpContext.Request.Form[BusinessConst.NAME_FIELD];
            cate.TypeID = Convert.ToInt32(this.HttpContext.Request.Form[BusinessConst.TYPE_FIELD]);

            CategoryRespository.UpdateCategory();
        }

        //
        //POST: /Category/Delete/5
        [AcceptVerbs(HttpVerbs.Post)]
        public void Delete(int id)
        {
            CategoryRespository.DeleteCategory(id);
        }
    }
}
